﻿/// <reference path="../core/jquery-1.4.2.min-vsdoc.js"/>
/// <reference path="../config/sw-config-default.js"/>
/// <reference path="../core/sw-prototype.js"/>
/// <reference path="../core/sw.js"/>
/// <reference path="../core/sw-control-core.js"/>

/***************************************************************************
jQuery Selector
NOTE: Created for SmartUI. 
Copyright 2010, Roy zhang
Features：
    1.实现下拉选择、选择列表功能。
    2.实现单选、多选列表。
    3.可以使用json数据源进行绑定，获取根据functioncode进行绑定
    4.实现默认取值、赋值操作；实现下拉选择列表的延迟加载功能
Update Note：

Needs：jquery.tmpl.js
****************************************************************************/

(function ($) {
    ///#region 设置
    var choosersetting = {
        container: ' <div/>'      //选择器标签
            , choosercss: 'chooser'    //选择器默认（下拉选择）样式
            , chooserlistcss: 'chooserlist' //选择列表样式
            , list: '<ul />'                //选项容器标签
            , id: '_chooser'
            , cssempty: 'empty'
            , item: '<li lv="${Key}">${Value}</li>' //选择项
            , multiitem: '<li class="multi" lv="${Key}">${Value}</li>'//多选的选择项
            , valueattr: 'lv'               //存储Value值的属性名
            , showinputint: '_txtshow'            //下拉选择时，显示控件的id后缀
            , split: iconfig.common.valuesplit                   //多选时值的分隔符
            , multicssname: 'ddlmulti'      //选择控件多选时的样式
            , cssname: 'ddl'                //选择控件的样式
    };
    ///#endregion
    $.fn.chooser = function (options, datasource) {
        /// <summary>选择控件</summary>
        /// <param name="options" type="Array">配置项</param>
        /// <param name="datasource" type="Json">数据源</param>
        ///#region 属性 
        options = $.extend({
            type: 'ddl'                 //类型,1.ddl(下拉选择)，2.list(列表选择)
            , ismulti: false            //是否允许多选
            , emptytype: 'none'        //空选项，none:无空项;all:显示文本“All”;select:显示文本“Select”;
            , ajax: null                     //ajax设置如：ajax:{url: null, data: null, fnsucess: null,fnerror:null}
            , lazyload: true                //下拉选择时，是否延迟加载（当选择控件有初始值时，则延迟加载无效）
            , cssname: null                 //ClassName
            , item: null //选择项
            , fnSelected: null              //fnSelected(value, chooser);
            , isBindData: true           //初始化时是否绑定数据，如果false时则生成结构
        }, options);
        options.css = $.extend({
            zindex: iconfig.chooser.css.zindex
                , width: iconfig.chooser.css.width
                , height: iconfig.chooser.css.height
                , left: iconfig.chooser.css.left            //对应x轴的偏移量
                , top: iconfig.chooser.css.top           //对象y轴的偏移量
                , fixwidth: iconfig.chooser.css.fixwidth
        }, options.css);
        options.text = $.extend({
            select: $iconst.controls.chooser.select
            , all: $iconst.controls.chooser.all
            , selectall: $iconst.controls.chooser.selectall
        }, options.text);
        ///#endregion
        ///#region 主体内容
        return this.each(function () {
            var chooser = $(this).attr("ctr", options.type), item;
            if (options.fnSelected)
                chooser.data('fnSelected', options.fnSelected);
            if (options.item) {
                item = options.item;
                chooser.data('item', item);
            }
            else
                item = options.ismulti ? choosersetting.multiitem : choosersetting.item;

            ///根据类型进行初始化
            if (options.type == 'ddl') {//当为下拉选择时，clone生成一个相同对象作为显示使用，原来的input隐藏
                var txt = chooser.clone(true).attr("id", chooser.attr("id") + choosersetting.showinputint)
                    .removeAttr("field").val('')
                    .addClass(options.ismulti ? choosersetting.multicssname : choosersetting.cssname)
                        .attr("readonly", -1).click(function () {//通过点击时加载数据，实现lazyload
                            var input = $(this);
                            if (input.data('ajax')) {
                                input.prev('#' + input.attr('id').Replace(choosersetting.showinputint, '')).chooserReload(input.data('ajax'));
                                input.removeData('ajax');
                            }
                            input.next('.' + choosersetting.choosercss).slideDown();
                        });
                chooser.hide().after(txt);

                if (options.isBindData && !datasource) {
                    txt.data('ajax', options.ajax);
                    var lazyload = true;
                    if (chooser.val().length > 0 || !options.lazyload)//当有初始值时，和不使用lazyload时，获取数据
                        lazyload = false;
                    chooser_build(txt, item, null, lazyload);
                }
                else
                    chooser_build(txt, item, datasource);
            }
            else {//为选择的list时
                chooser.hide();
                chooser_build(chooser, item, datasource);
            }
            chooser.data('ismulti', options.ismulti);
        });
        ///#endregion

        ///#region 私有方法
        function chooser_build(chooser, item, datas, lazyload) {
            /// <summary>生成chooser</summary>
            /// <param name="chooser" type="DomOrJQDom">选择控件，包括原始和动态生成的对象</param>           
            /// <param name="datas" type="Json">json数据源</param>
            /// <param name="isclickload" type="Bool">是否为点击时加载(延迟加载的执行)</param>
            var chooserid = chooser.attr("id").Replace(choosersetting.showinputint, ''); //获取原始选择器的值
            var id = chooserid + choosersetting.id, list = $(choosersetting.list);

            ddl = $(choosersetting.container).attr("id", id).attr("ctr", options.type); //创建容器项
            if (options.type == "ddl")//使用弹出效果
            {
                ictrcore.upselector(chooser, ddl, options.css).addClass(options.cssname || choosersetting.choosercss);
                if (options.ismulti) {
                    var btn = $(document.createElement('a')).text(options.text.selectall).click(function () {
                        var btn = $(this), items = btn.parent().next().children('li');
                        if (btn.hasClass('chked')) {
                            items.removeClass('selected');
                            $(chooserid + choosersetting.showinputint).val('');
                            chooser_selected($(chooserid), '');
                        }
                        else {
                            var sbValus = new StringBuilder();
                            var sbText = new StringBuilder();
                            items.each(function (i) {
                                var select = $(this);
                                value = select.attr(choosersetting.valueattr);
                                if (value) {
                                    sbValus.append(value);
                                    sbText.append(select.text());
                                }
                                items.addClass('selected');
                            })
                            $(chooserid + choosersetting.showinputint).val(sbText.toString(choosersetting.split)).focus();
                            value = sbValus.toString(choosersetting.split);
                            chooser_selected($(chooserid), value);
                        }
                        btn.toggleClass('chked');
                    });
                    $(document.createElement('div')).addClass(choosersetting.cssempty).append(btn).appendTo(ddl);
                }
                else
                    if (options.emptyitem != 'none') {
                        var btn = $(document.createElement('a')).text(options.emptyitem == 'all' ? options.text.all : options.text.select)
                        $(document.createElement('div')).addClass(choosersetting.cssempty).append(btn)
                        .click(function () {
                            $(chooserid).chooserSetValue('').nextAll(chooserid + choosersetting.id).fadeOut('fast');
                        }).appendTo(ddl);
                    }
            }
            else
                ddl.addClass(options.cssname || choosersetting.chooserlistcss);
            //创建选择列表

            chooserid = '#' + chooserid;
            chooser.after(ddl.append(list));
            ///#region 使用repeat生成选项
            if (options.isBindData) {
                if (datas)//直接使用json数据源始
                    chooser_bindselect(options.ismulti, chooserid, ictrcore.teml(list, item, datas), options.type);
                else {
                    if (!lazyload) {
                        var ismulti = options.ismulti, type = options.type;
                        bindByAjax(options.ajax, list, item, function (data, list) { chooser_bindselect(ismulti, chooserid, list, type); });
                    }
                }
            }
            ///#endregion
        }
        ///#endregion
    };
    ///#region 内部方法
    function bindByAjax(ajax, list, item, fn) {
        /// <summary>ajax 绑定数据Smart UI专用,移植时去掉即可，或者扩展ajax方法</summary>
        if (ajax && ajax.url)
            ictrcore.temlbyAjax(list, item, ajax.url, ajax.data, fn);
    }
    function chooser_bindselect(ismulti, chooserid, items, type, chooser) {
        if (ismulti)
            chooser_mulititemselect(chooserid, items, type, chooser);
        else
            chooser_itemselect(chooserid, items, type, chooser);
    }
    function chooser_itemselect(id, items, type, chooser) {
        /// <summary>单选事件绑定</summary>
        /// <param name="id" type="DomOrJqueryObj">原始选择控件id</param>           
        /// <param name="list" type="JQDom">json数据源</param>
        //        if (type == 'ddl')
        //            list = $(id + choosersetting.id + ' li')
        items.click(function () {//点击时赋值
            var item = $(this), isselected = item.hasClass("selected"), value = '';
            item.parent().find('li.selected').removeClass("selected");
            if (!isselected) {
                item.addClass("selected");
                value = item.attr(choosersetting.valueattr) || '';
            }
            if (type == 'ddl')
                $(id + choosersetting.id).fadeOut('fast');
            $(id + choosersetting.showinputint).val(item.text()).focus();
            chooser_selected($(id), value);
        });
        //将设置初始值
        setSelected(chooser, id, items, type);
    }
    function chooser_mulititemselect(id, items, type, chooser) {
        items.click(function () {//点击时赋值
            var item = $(this);
            var isSelected = !item.hasClass("selected");
            item.toggleClass("selected", isSelected);
            var value;
            var select;
            var sbValus = new StringBuilder();
            var sbText = new StringBuilder();
            item.parent().find('li.selected').each(function () {
                select = $(this);
                value = select.attr(choosersetting.valueattr);
                if (value) {
                    sbValus.append(value);
                    sbText.append(select.text());
                }
            });
            $(id + choosersetting.showinputint).val(sbText.toString(choosersetting.split)).focus();
            value = sbValus.toString(choosersetting.split);
            chooser_selected($(id), value);
        });
        //将设置初始值
        setSelected(chooser, id, items, type);
    }

    function chooser_selected(chooser, value) {
        var fnSelected = chooser.data('fnSelected');
        if (fnSelected) {
            var oldvalue = chooser.val();
            chooser.val(value);
            fnSelected(value, oldvalue, chooser);
        }
        else
            chooser.val(value);
    }

    function setSelected(chooser, id, list, type) {
        if (!chooser)
            chooser = $(id);
        var strValue = chooser.val(), ishasvalue;
        if (list.length > 0) {
            list.filter('li.selected').removeClass('selected');
            if (strValue.length > 0) {
                var arrValues = strValue.split(choosersetting.split);
                if (arrValues.length > 0) {
                    var sbFilter = new StringBuilder();
                    for (var i = 0; i < arrValues.length; i++) {
                        strValue = arrValues[i].trim();
                        if (strValue.length > 0) {
                            sbFilter.append("li.[lv ='").append(strValue).append("']").append(',');
                        }
                    }
                    if (sbFilter.strings.length > 1) {
                        var selects = list.filter(sbFilter.removeLast().toString());
                        if (selects.length > 0) {
                            if (type == 'list')
                                selects.addClass("selected");
                            else {
                                var sbText = new StringBuilder();
                                selects.each(function () {
                                    var item = $(this);
                                    sbText.append(item.text()).append(choosersetting.split);
                                    item.addClass("selected");
                                });
                                $(id + choosersetting.showinputint).val(sbText.removeLast());
                            }
                            ishasvalue = true;
                        }
                    }
                }
            }
        }
        if (!ishasvalue) {
            chooser.val('');
            if (type !== 'list')
                $(id + choosersetting.showinputint).val('');
        }
    }
    ///#endregion
    $.fn.chooserSetValue = function (value) {
        /// <summary>选择控件</summary>
        /// <param name="value" type="String">配置项</param>
        /// <param name="type" type="String">下拉对象类型</param>
        var id = '#' + this.val(value).attr("id");
        setSelected(this, id, $(id + choosersetting.id + " > ul > li"), this.attr('ctr'));
        return this;
    }
    $.fn.chooserReload = function (ajax, datas) {
        var id = '#' + this.attr("id");
        var list = this.siblings(id + choosersetting.id).children('ul');
        list.html('');
        var ismulti = this.data('ismulti'), type = this.attr('ctr')
        , item = this.data('item') || (ismulti ? choosersetting.multiitem : choosersetting.item);

        if (datas)//直接使用json数据源始
            chooser_bindselect(ismulti, id, ictrcore.teml(list, item, datas), type, this);
        else
            bindByAjax(ajax, list, item, function (data, list) { chooser_bindselect(ismulti, id, list, type); });
        return this;
    }
})(jQuery);


